//popup menu

CloudDisk.ContextMenu = function(config){
    this.el = null;
	this.targetEl = null;
	
	this._init(config);
};

CloudDisk.ContextMenu.prototype = {
	_init: function(config){
		var el = $('<div class="context-menu"></div>').appendTo(document.body);
		var that = this;
	
		//hide menu when mousedown outside
		$(document).on('mousedown', function(e){
			var target = $(e.target);     
			if (!target.is(config.selector) && target.closest(config.selector).length < 1) {                
				el.hide();            
			}
		});
		
		//bind handler for menu items
		el.mousedown(function(e){
			var index = $(e.target).attr('index');
			if(index){
				config.items[parseInt(index)].handler.apply(this, [that.targetEl]);
				el.hide();
			}
		});
		
		this.el = el;
		this.createItems(config.items);
	},
	show: function(target, pos){
		var maxX = $(window).scrollLeft() + $(window).width();
		var maxY = $(window).scrollTop() + $(window).height();
		var menuPos = {};
		
		if(pos.x > maxX - this.el.width()){
			menuPos.left = pos.x - this.el.width();
		} else {
			menuPos.left = pos.x + 2;
		}

		if(pos.y > maxY - this.el.height()){
			menuPos.top = pos.y - this.el.height();						
		} else {
			menuPos.top = pos.y + 2;
		}
		
		this.targetEl = $(target);
		this.el.show();
		this.el.css(menuPos);
	},
	
	createItems: function(items){
		this.el.empty();
		var wrapper = $('<ul></ul>');	
		for(var i = 0; i < items.length; ++i){
			var item = items[i];
			if(item != '-'){
				$('<li><a index="' + i + '">' + item.title + '</a></li>').appendTo(wrapper);
			} else {//separator
				$('<li class="separator"></li>').appendTo(wrapper);
			}
			
		}		
		wrapper.appendTo(this.el);			
	}
};
